package com.example.domain.entity;

import com.example.domain.entity.enums.PricingRuleType;
import javax.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.time.LocalDateTime;

/**
 * 促销规则实体类
 * 
 * 优先级（Priority）说明：
 * - Priority 1：商品级（单品折扣、会员价）- 最优先
 * - Priority 2：组合优惠
 * - Priority 3：店铺级/订单级（满减、阶梯满减）
 * - Priority 4：用户级（优惠券、红包，用户主动使用）- 未来扩展
 * 
 * 计算顺序：数值越小优先级越高，按 Priority 1 → 2 → 3 → 4 顺序计算
 * 
 * 排他性规则：
 * - 同优先级、同对象（如同商品、同活动范围），只能有一个规则 enabled=true
 * - 启用规则时，系统自动禁用冲突规则
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "pricing_rules")
public class PricingRule extends SoftDeleteEntity {

    @Id
    @Column(name = "id", length = 26)
    private String id;

    @Column(name = "name", length = 100, nullable = false)
    private String name;

    @Enumerated(EnumType.STRING)
    @Column(name = "type", length = 50, nullable = false)
    private PricingRuleType type;

    @Column(name = "priority")
    private Integer priority = 0;

    @Column(name = "enabled", columnDefinition = "TINYINT(1) DEFAULT 1")
    private Boolean enabled = true;

    @Column(name = "valid_from", nullable = false)
    private LocalDateTime validFrom;

    @Column(name = "valid_to")
    private LocalDateTime validTo;
    
    /**
     * 根据类型自动设置优先级
     */
    public void setType(PricingRuleType type) {
        this.type = type;
        if (this.priority == null || this.priority == 0) {
            this.priority = getDefaultPriority(type);
        }
    }
    
    /**
     * 获取规则类型对应的默认优先级
     */
    private Integer getDefaultPriority(PricingRuleType type) {
        switch (type) {
            case ITEM_DISCOUNT:
                return 1;  // 商品级，最优先
            case THRESHOLD_DISCOUNT:
                return 3;  // 订单级
            default:
                return 4;
        }
    }
}

